package com.das.mechanic_base.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.res.ResourcesCompat;

import com.das.mechanic_base.R;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3TimeUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.haibin.calendarview.MonthViewPager;
import com.haibin.calendarview.WeekViewPager;
import com.umeng.analytics.MobclickAgent;
import com.zyyoona7.wheel.WheelView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static android.view.View.VISIBLE;

public class X3BottomTimeTaskDialog extends X3BaseBottomSheetDialog implements View.OnClickListener, CalendarView.OnMonthChangeListener, CalendarView.OnCalendarSelectListener, WheelView.OnItemSelectedListener<String> {

    private TextView tv_cancel;
    private TextView tv_affirm;
    private TextView tv_date;
    private CalendarView cv_view;
    private ImageView iv_left;
    private ImageView iv_right;
    private RelativeLayout rl_show;
    private ImageView iv_icon;
    private RelativeLayout rl_top;
    private String inputDate;//选中的时间
    private String today;//当前的时间

    private String carTime;
    private String selectTime = "";
    private MonthViewPager mMonthView;
    private WeekViewPager mWeekPager;
    private int weekBarHeight;
    private int weekHeight;
    private ValueAnimator monthAnim;
    private ValueAnimator weekAnim;

    private WheelView<String> wv_hour;//设置小时
    private WheelView<String> wv_second;//设置分数

    private List<String> hours = new ArrayList<>();
    private List<String> seconds = new ArrayList<>();
    private String isTime;//如果先选日期，获取选中的日期，拼接到时间前面
    private X3PointDialog backDialog;//提醒的弹窗
    private int newTime;//当前时间的下个10分钟
    private boolean isSelect;//判断是否已经设置了提醒时间,true:设置 false：没设置
    private Typeface font;

    public X3BottomTimeTaskDialog(@NonNull Context context) {
        super(context);
    }


    //判断是否已经设置了时间
    public void dateIsSelect(boolean isSelects) {
        this.isSelect = isSelects;
    }

    /**
     * 获取提醒时间分两种清空
     * 第一种：无提醒的时候，默认获取系统当前时间，+一个小时
     * 第二种：如果设置了提醒时间， 进来之后显示提醒的时间
     */
    public void setTimeDate(String selectTime) {
        this.selectTime = selectTime;
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        tv_cancel = getView(R.id.tv_cancel);
        tv_affirm = getView(R.id.tv_affirm);
        tv_date = getView(R.id.tv_date);
        cv_view = getView(R.id.cv_view);
        iv_left = getView(R.id.iv_left);
        iv_right = getView(R.id.iv_right);
        rl_show = getView(R.id.rl_show);
        iv_icon = getView(R.id.iv_icon);
        rl_top = getView(R.id.rl_top);
        wv_hour = getView(R.id.wv_hour);
        wv_second = getView(R.id.wv_second);

        tv_cancel.setOnClickListener(this);
        tv_affirm.setOnClickListener(this);
        iv_right.setOnClickListener(this);
        iv_left.setOnClickListener(this);
        rl_show.setOnClickListener(this);
        for (int i = 0; i < 24; i++) {
            hours.add(i < 10 ? "0" + i : i + "");
        }
//        for (int i = 0; i < 60; i++) {
//            seconds.add(i < 10 ? "0" + i : i + "");
//        }
        seconds.add("00");
        seconds.add("10");
        seconds.add("20");
        seconds.add("30");
        seconds.add("40");
        seconds.add("50");

        font = ResourcesCompat.getFont(mContext, R.font.din_text_type);

        wv_hour.setTypeface(font);

        wv_second.setTypeface(font);

        wv_hour.setData(hours);
        wv_second.setData(seconds);
        //如果为null，表明是无提醒进来，目前已经设置了时间，进来也走着，待确定需求
        if (TextUtils.isEmpty(selectTime)) {
            //获取系统时间
            java.util.Calendar calendar = java.util.Calendar.getInstance();
            int minute = calendar.get(java.util.Calendar.MINUTE);
            int hour = calendar.get(java.util.Calendar.HOUR_OF_DAY);
            Log.e("TAG", "--minute---" + minute + "----hour--" + hour);
            if (hour == 24) {
                wv_hour.setSelectedItemPosition(0);
            } else {
                wv_hour.setSelectedItemPosition(hour);
            }

            if (0 <= minute && minute < 10) {
                newTime = 1;
            } else if (10 <= minute && minute < 20) {
                newTime = 2;
            } else if (20 <= minute && minute < 30) {
                newTime = 3;
            } else if (30 <= minute && minute < 40) {
                newTime = 4;
            } else if (40 <= minute && minute < 50) {
                newTime = 5;
            } else if (50 <= minute && minute < 60) {
                newTime = 0;
                wv_hour.setSelectedItemPosition(hour+1);
            }

            wv_second.setSelectedItemPosition(newTime);
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//如果用到别的就用特定
            //字符表示，如星期F
            today = sdf.format(d);
            //title显示的当前年月
            tv_date.setText(X3DateUtils.MonthWithYear(cv_view.getCurYear() + "-" + cv_view.getCurMonth() + "-01 00:00:00"));
            //获取选中时间
            inputDate = cv_view.getCurYear() + "-" +
                    (cv_view.getCurMonth() < 10 ? "0" + cv_view.getCurMonth() : cv_view.getCurMonth()) + "-" +
                    (cv_view.getCurDay() < 10 ? "0" + cv_view.getCurDay() : cv_view.getCurDay()) +
                    " " + wv_hour.getSelectedItemData() + ":" + wv_second.getSelectedItemData() + ":00";
        } else {
            //显示已经设置提醒的时间,这里的逻辑暂时未使用到
//            today = selectTime;
//            inputDate = selectTime;
//            try {
//                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date date = format.parse(selectTime);
//                java.util.Calendar calendar1 = java.util.Calendar.getInstance();
//                calendar1.setTime(date);
//                int year = calendar1.get(java.util.Calendar.YEAR);
//                int month = calendar1.get(java.util.Calendar.MONTH + 1);
//                int dates = calendar1.get(java.util.Calendar.DATE);
//                wv_hour.setSelectedItemPosition(month);
//                wv_second.setSelectedItemPosition(dates);
//                tv_date.setText(year + "年" + month + "月");
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            Log.e("TAG", "日期：" + selectTime);
        }

        //默认显示当前的分钟
        wv_hour.setOnItemSelectedListener(this);
        wv_second.setOnItemSelectedListener(this);

        mMonthView = cv_view.getMonthViewPager();
        mWeekPager = cv_view.getWeekViewPager();

        cv_view.setOnMonthChangeListener(this);
        cv_view.setOnCalendarSelectListener(this);

        cv_view.post(() -> {
            weekBarHeight = X3ScreenUtils.dipToPx(30, mContext);
            weekHeight = X3ScreenUtils.dipToPx(40, mContext);
            initMonthWeekAnim(mMonthView.getLayoutParams().height);
            // 切换成周视图
            rl_show.performClick();
        });

    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_task_time_bottom_dialog;
    }

    /**
     * 初始化日历切换 月 周 日历动画
     *
     * @param height
     */
    private void initMonthWeekAnim(int height) {
        monthAnim = ValueAnimator.ofFloat(weekHeight, height);
        monthAnim.setDuration(300);
        monthAnim.addUpdateListener(valueAnimator -> {
            ViewGroup.LayoutParams layoutParams = mMonthView.getLayoutParams();
            float animatedValue = (float) valueAnimator.getAnimatedValue();
            layoutParams.height = (int) animatedValue;
            mMonthView.setLayoutParams(layoutParams);

            float precent = (animatedValue - weekHeight) * 100 / (height - weekHeight) * 0.01f;
            RelativeLayout.LayoutParams top_layout = (RelativeLayout.LayoutParams) rl_top.getLayoutParams();
            top_layout.height = (int) (weekBarHeight * precent);
            rl_top.setLayoutParams(top_layout);
        });
        monthAnim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                isHideShowWeek(false);
            }
        });

        // 70的理由是  周视图高度 40 + weekbar 30
        weekAnim = ValueAnimator.ofFloat(height, weekHeight);
        weekAnim.setDuration(300);
        weekAnim.addUpdateListener(valueAnimator -> {
            ViewGroup.LayoutParams layoutParams = mWeekPager.getLayoutParams();
            float animatedValue = (float) valueAnimator.getAnimatedValue();
            layoutParams.height = (int) animatedValue;
            mWeekPager.setLayoutParams(layoutParams);

            float precent = (height - animatedValue) * 100 / (height - weekHeight) * 0.01f;
            RelativeLayout.LayoutParams top_layout = (RelativeLayout.LayoutParams) rl_top.getLayoutParams();
            top_layout.height = (int) (weekBarHeight * (1 - precent));
            rl_top.setLayoutParams(top_layout);
        });
        weekAnim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                isHideShowWeek(true);
            }
        });
    }

    /**
     * 是显示月视图 还是显示周视图
     *
     * @param isShow
     */
    private void isHideShowWeek(boolean isShow) {
        mWeekPager.setVisibility(isShow ? VISIBLE : View.GONE);
        mMonthView.setVisibility(isShow ? View.GONE : VISIBLE);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_cancel) {
            dismiss();
        } else if (id == R.id.tv_affirm) {// 下一步

            boolean timeCompareSize = X3TimeUtils.getNewTimeCompareSize(today, inputDate);
            int chaTime = X3TimeUtils.countTime(inputDate, today);
            Log.e("TAG", "-----tody------:" + today + "-----------inputDate:---" + inputDate + "------相差：" + chaTime);
            if (!timeCompareSize) {
                X3ToastUtils.showMessage(mContext.getString(R.string.x3_no_today_tips));
                return;
            }

            if (chaTime > 90) {
                if (backDialog == null) {
                    backDialog = new X3PointDialog(mContext, "", mContext.getString(R.string.x3_dialog_reminder_time), mContext.getString(R.string.x3_back), mContext.getString(R.string.x3_no_push_required));
                }
                backDialog.show();
                backDialog.setiBtnClick(new X3PointDialog.IBtnClick() {
                    @Override
                    public void iBtnAffirmClick() {
                        if (iOnClickTime != null) {
                            iOnClickTime.iOnClickTimeTask(inputDate);
                        }
                        dismiss();
                    }

                    @Override
                    public void iBtnCancelClick() {

                    }
                });
                return;
            }
            if (iOnClickTime != null) {
                iOnClickTime.iOnClickTimeTask(inputDate);
            }
            dismiss();
        } else if (id == R.id.iv_left) {
            if (cv_view != null) {
                cv_view.scrollToPre();
            }
        } else if (id == R.id.iv_right) {
            if (cv_view != null) {
                cv_view.scrollToNext();
            }
        } else if (id == R.id.rl_show) {// 切换周月视图
            if (mMonthView.getVisibility() != VISIBLE) {
                mWeekPager.setVisibility(View.GONE);
                mMonthView.setVisibility(VISIBLE);
                monthAnim.start();
                iv_icon.setRotation(-180);
            } else {
                weekAnim.start();
                iv_icon.setRotation(0);
            }
        }
    }

    IOnClickTime iOnClickTime;

    public void setiOnClickTime(IOnClickTime iOnClickTime) {
        this.iOnClickTime = iOnClickTime;
    }

    @Override
    public void onItemSelected(WheelView<String> wheelView, String data, int position) {
        //这里的判断是解决用户先选日期在选时间，不能实时更新的问题
        if (!X3StringUtils.isEmpty(isTime)) {
            inputDate = isTime + wv_hour.getSelectedItemData() + ":" + wv_second.getSelectedItemData() + ":00";
        } else {
            inputDate = cv_view.getCurYear() + "-" +
                    (cv_view.getCurMonth() < 10 ? "0" + cv_view.getCurMonth() : cv_view.getCurMonth()) + "-" +
                    (cv_view.getCurDay() < 10 ? "0" + cv_view.getCurDay() : cv_view.getCurDay()) +
                    " " + wv_hour.getSelectedItemData() + ":" + wv_second.getSelectedItemData() + ":00";
        }
        Log.e("TAG", "这个时间：" + inputDate);
    }

    public interface IOnClickTime {
        void iOnClickTimeTask(String selectTim);
    }

    @Override
    public void onMonthChange(int year, int month) {
        tv_date.setText(X3DateUtils.MonthWithYear(year + "-" + month + "-01 00:00:00"));
    }

    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        isTime = calendar.getYear() + "-" +
                (calendar.getMonth() < 10 ? "0" + calendar.getMonth() : calendar.getMonth()) + "-" +
                (calendar.getDay() < 10 ? "0" + calendar.getDay() : calendar.getDay()) +
                " ";
        inputDate = calendar.getYear() + "-" +
                (calendar.getMonth() < 10 ? "0" + calendar.getMonth() : calendar.getMonth()) + "-" +
                (calendar.getDay() < 10 ? "0" + calendar.getDay() : calendar.getDay()) +
                " " + wv_hour.getSelectedItemData() + ":" + wv_second.getSelectedItemData() + ":00";
        Log.e("TAG", "选择的日期：" + inputDate);

    }
    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("待办事项提醒我弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("待办事项提醒我弹窗");
    }
}